package com.luatos.iot.regproxy.module;

import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Lang;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.lang.util.Regex;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Ok;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailRequest;
import com.aliyuncs.iot.model.v20180120.QueryDeviceDetailResponse;
import com.aliyuncs.iot.model.v20180120.RegisterDeviceRequest;
import com.aliyuncs.iot.model.v20180120.RegisterDeviceResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.luatos.iot.regproxy.bean.AliyunIotProduct;

@At("/reg")
@Fail("http:500")
@IocBean(create = "init")
public class AliyunIotRegModule {
	
	private static Log log = Logs.get();
	
	@Inject
	protected PropertiesProxy conf;

	@At
	@Ok("json:tidy")
	public NutMap aliyun(String dev, String key, String sign, String ranstr) {
		// 首先, 检查必要的参数
		if (Strings.isBlank(dev) || Strings.isBlank(key)) {
			log.debug("miss dev/key/sign/ranstr");
			return new NutMap("msg", "miss dev/key/sign");
		}
		if (!Regex.match("^[a-zA-z0-9]{10,20}", dev)) {
			log.info("非法的设备名称" + dev);
			return new NutMap("msg", "bad dev name");
		}
		// 根据key(ProductKey)查找项目
		AliyunIotProduct product = conf.make(AliyunIotProduct.class, "luatos.regproxy.aliyuniot." + key + ".");
		if (Strings.isBlank(product.endpoint)) {
			log.debug("no such product key=" + key);
			return new NutMap("msg", "no such product key");
		}
		product.productKey = key;
		// 计算签名, md5算法应该是所有设备都能支持的
		// String mysign = Lang.md5(dev + product.productKey + product.signKey + Strings.sBlank(ranstr));
		// if (!mysign.equalsIgnoreCase(sign)) {
		// 	log.debugf("sign not match expect %s but %s", mysign, sign);
		// 	return new NutMap("msg", "sign not match");
		// }
		
		//初始化SDK客户端
		IClientProfile profile = DefaultProfile.getProfile(product.endpoint, product.accessKey, product.accessSecret);
		DefaultAcsClient client = new DefaultAcsClient(profile);

		String deviceSecret = null;
		try {

			// 到Device表查查有没有现成的
			QueryDeviceDetailRequest qdd = new QueryDeviceDetailRequest();
			qdd.setDeviceName(dev);
			qdd.setProductKey(product.productKey);
			QueryDeviceDetailResponse qdd_resp = client.getAcsResponse(qdd);
			if (qdd_resp.getSuccess() == Boolean.TRUE) {
				deviceSecret = qdd_resp.getData().getDeviceSecret();
			}
			else {
				// 那就注册吧
				RegisterDeviceRequest rd = new RegisterDeviceRequest();
				rd.setDeviceName(dev);
				rd.setProductKey(product.productKey);
				RegisterDeviceResponse rd_resp = client.getAcsResponse(rd);
				if (rd_resp.getSuccess() == Boolean.TRUE) {
					deviceSecret = rd_resp.getData().getDeviceSecret();
				}
				else {
					log.warn("注册新设备失败" + Json.toJson(rd_resp));
				}
			}
		} catch (Exception e) {
			log.error("出错啦!!!", e);
			return new NutMap("msg", "server error");
		}
		if (Strings.isBlank(deviceSecret)) {
			log.warn("未能拿到设备密钥:" + dev);
			return new NutMap("msg", "server error2");
		}
		
		return new NutMap("secret", deviceSecret);
	}
	
	public void init() throws ClientException {
		DefaultProfile.addEndpoint("cn-shanghai", "cn-shanghai", "Iot", "iot.cn-shanghai.aliyuncs.com");
	}
}

